<?php
class ModelFaStore extends Model {
	public function addStore($data) {
      	$this->db->query("INSERT INTO " . DB_PREFIX . "fa_store SET name = '". $this->db->escape($data['name']) . "', address = '" . $this->db->escape($data['address']) . "'");
		
		$store_id = $this->db->getLastId();

		$this->cache->delete('fa_store');
	}
	
	public function editStore($store_id, $data) {
      	$this->db->query("UPDATE " . DB_PREFIX . "fa_store SET name = '". $this->db->escape($data['name']) . "', address = '" . $this->db->escape($data['address']) . "'");

		$this->cache->delete('fa_store');
	}
	
	public function deleteStore($store_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "fa_store WHERE store_id = '" . (int)$store_id . "'");

		$this->cache->delete('fa_store');
	}	
	
	public function getStore($store_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "fa_store WHERE store_id = '" . (int)$store_id . "'");
		
		return $query->row;
	}
	
	public function getStores($data = array()) {
		$sql = "SELECT * FROM " . DB_PREFIX . "fa_store";

		if (!empty($data['filter_name'])) {
			$sql .= " WHERE name LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
		}

		if (!empty($data['filter_short_name'])) {
			$sql .= " WHERE short_name LIKE '%" . $this->db->escape($data['filter_short_name']) . "%'";
		}
		
		$sort_data = array(
			'name',
			'sort_order'
		);	
		
		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];	
		} else {
			$sql .= " ORDER BY name";	
		}
		
		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}
		
		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}					

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}	
		
			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}				
		
		$query = $this->db->query($sql);
	
		return $query->rows;
	}
	
	public function getTotalStores() {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "fa_store");
		
		return $query->row['total'];
	}	
	
}
?>